package com.jinlia.show.modules.wxapp.websocket;

import lombok.extern.slf4j.Slf4j;
import org.springframework.util.CollectionUtils;
import org.springframework.web.socket.WebSocketSession;

import java.io.IOException;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;

@Slf4j
public class WebSocketSessionManager {
    /**
     * 保存连接 session 的地方
     */
    public static ConcurrentHashMap<String, Set<ChatWebSocketSession>> SESSION_POOL = new ConcurrentHashMap<>();

    /**
     * 添加 session
     *
     * @param userId
     */
    public static void add(String userId, WebSocketSession session) {
        log.info("建立链接={}",userId);
        if (SESSION_POOL.containsKey(userId)) {
            Set<ChatWebSocketSession> chatWebSocketSessions = SESSION_POOL.get(userId);
            chatWebSocketSessions.add(new ChatWebSocketSession(session, userId));
        } else {
            Set<ChatWebSocketSession> chatWebSocketSessions = new HashSet<>();
            chatWebSocketSessions.add(new ChatWebSocketSession(session, userId));
            SESSION_POOL.put(userId, chatWebSocketSessions);
        }
        // 添加 session

    }


    /**
     * 删除并同步关闭连接
     *
     * @param key
     */
    public static void removeAndClose(String key, WebSocketSession session) {
        log.info("删除链接={}",key);
        if (!SESSION_POOL.containsKey(key)) {
            //用户已被挤掉
            log.info("用户({})已被挤掉!!!", key);
            return;
        }
        Set<ChatWebSocketSession> chatWebSocketSessions = SESSION_POOL.get(key);
        log.info("用户({})链接链接数={}", key,chatWebSocketSessions.size());
        Optional<ChatWebSocketSession> first = chatWebSocketSessions.stream().filter(i -> i.webSocketSession.equals(session)).findFirst();
        first.ifPresent(i->{
            chatWebSocketSessions.remove(i);
        });
    }

    public static class ChatWebSocketSession {
        private WebSocketSession webSocketSession;
        private String userId;

        public ChatWebSocketSession(WebSocketSession webSocketSession, String userId) {
            this.webSocketSession = webSocketSession;
            this.userId = userId;
        }

        public WebSocketSession getWebSocketSession() {
            return webSocketSession;
        }
    }
}
